<?php defined('SYSPATH') or die('No direct script access.');

/**
 *User: idoiwill
 *Email: xslt@idoiwill.com
 *Blog: http://www.idoiwill.com
 *DateTime: 2017/5/17 12:16
 */
class Controller_Pc_Api_Standard_Car extends Controller_Pc_Api_Base
{
    public function before()
    {
        parent::before();
    }

    /**
     * @desc 获取轮播图
     */
    public function action_get_rolling_ad()
    {
        $result = DB::select()->from('xcx_ads')->where('prefix','=','s_car_index')
            ->order_by('displayorder','asc')->execute()->as_array();
        foreach($result as &$v){
            //判断产品类型
            if($v['typeid'] == 3){
                $v['url'] = '/stpage/cars/pages/carShow/carShow';
                $mod = DB::select('litpic')->from('car');
            }
            if(!empty($mod)){
                $row = $mod ->where('id','=',$v['proid'])->execute()->current();
                //增加图片绝对访问地址
                $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($row['litpic']);
            }
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
    //首页推荐
    public function action_index_recommend()
    {
        $p = intval($this->request_body->content->p) or $p = 1;
        $pagesize = intval($this->request_body->content->pagesize) or $pagesize = 4;
        $result = Taglib_Car::query(array('flag' => 'order', 'row' => $pagesize));
        foreach ($result as &$item)
        {
            $item['litpic'] = Common::img($item['litpic']);
        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 获取推荐租车
     */
    public  function action_get_tuijian()
    {
        //条数
        $pagesize = intval($this->request_body->content->pagesize);
        $params = array(
            'pagesize' => $pagesize
        );
        $result = Model_Api_Standard_Car::search($params);
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 获取热门目的地
     */
    public function action_hot_city()
    {
        $result = Model_Api_Standard_Car::hot_dest();
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * 按目的地关键词搜索
     */
    public function action_search_city()
    {
        $keyword = St_Filter::remove_xss($this->request_body->content->keyword);
        if (!empty($keyword))
        {
            $result = Model_Api_Standard_Car::search_dest($keyword);

            $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
        }


    }
    /**
     * 获取租车车型
     */
    public function action_carkindlist()
    {
        $result = Model_Api_Standard_Car::carkindlist();

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
    /**
     * @desc 栏目信息
     */
    public function action_channel()
    {
        $result = Model_Api_Standard_Car::channel();

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
    //查询条件
    public function action_query_condition()
    {
        $result = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量优先'),
                array('id' => 4, 'name' => '人气推荐')
            ),
            'price' => array('name' => '价格', 'child' => array()),
            'attribute' => array(),
        );
        //价格
        $result['price']['child'] = DB::select()->from('car_pricelist')->where('webid', '=', 0)->execute()->as_array();
        foreach ($result['price']['child'] as &$row)
        {
            if ($row['min'] != '' && $row['max'] != '')
            {
                $row['name'] = Currency_Tool::symbol() . $row['min'] . '-' . Currency_Tool::symbol() . $row['max'];
            }
            else if ($row['min'] == '')
            {
                $row['name'] = Currency_Tool::symbol() . $row['max'] . '以下';
            }
            else if ($row['max'] == '')
            {
                $row['name'] = Currency_Tool::symbol() . $row['min'] . '以上';
            }
        }
        $result['attribute'] = DB::select('id', array('attrname', 'name'))->from('car_attr')->where('pid', '=', 0)->and_where('isopen', '=', 1)->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->execute()->as_array();
        foreach ($result['attribute'] as &$item)
        {
            $item['child'] = DB::select('id', array('attrname', 'name'))->from('car_attr')->where('pid', '=', $item['id'])->and_where('isopen', '=', 1)->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')->execute()->as_array();

        }
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    public function action_general_query()
    {
        $params = array(
            'pagesize' => $this->request_body->content->pagesize,
            'keyword' => $this->request_body->content->keyword,
            'starttime' => strtotime($this->request_body->content->starttime),
            'endtime' => strtotime($this->request_body->content->endtime),
            'carkindid' => $this->request_body->content->carkindid,
        );
        $path = $this->request_body->content->path;
        list($params['destpy'], $params['priceid'], $params['sorttype'], $params['attrid'], $params['page']) = explode('-', $path);

        $result = Model_Api_Standard_Car::search($params);
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }
    /**
     * @desc 获取租车列表
     */
    public function action_list()
    {
        //条数
        $pagesize = intval($this->request_body->content->pagesize);
        //页码
        $page = intval($this->request_body->content->page);
        //关键词
        $keyword = Common::remove_xss($this->request_body->content->keyword);
        $params = array(
            'page'     => $page,
            'pagesize' => $pagesize,
            'keyword'  => $keyword,
        );
        $result = Model_Api_Standard_Car::search($params);

        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
    }

    /**
     * @desc 租车详情
     */
    public function action_detail()
    {
        $params['id'] = intval($this->request_body->content->productid);
        $params['userid'] = intval($this->request_body->content->userid);
        if($params['id'])
        {
            $result = Model_Api_Standard_Car::detail($params);

            if (empty($result))
            {
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key'], false, '查询租车失败', '查询租车失败');
            } else
            {
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            }

        }
    }

    /**
     * @desc 获取报价
     */
    public function action_price()
    {

        $suitid = intval($this->request_body->content->suit_id);
        $row = intval($this->request_body->content->row);

        $year = intval($this->request_body->content->year);
        $month = intval($this->request_body->content->month);

        if ($suitid)
        {
            $query = DB::select()->from('car_suit_price')
                ->where('suitid', '=', $suitid)
                ->and_where('supplier_channel_id', '=', 1)
            ;
            if (empty($year) && empty($month))
            {
                $day = strtotime(date('Y-m-d'));
                $query->and_where('day', '>=', $day);
            }
            else
            {
                $need_full_days = true;
                $start = strtotime("$year-$month-1");
                $days = date('t', $start);
                $end = strtotime("$year-$month-$days");
                $query->and_where('day', '>=', $start);
                $query->and_where('day', '<=', $end);
            };
            if ($row)
            {
                $query->limit($row);
            }


            $result = $query->execute()->as_array();



            $now = strtotime(date('Y-m-d'));

            foreach ($result as &$row)
            {
                $row['digital'] = intval(date('d', $row['day']));
                //过期数据
                if ($row['day'] < $now)
                {
                    $row['adultprofit'] = 0;
                    $row['adultbasicprice'] = 0;
                    $row['adultprice'] = 0;
                }
                $row['date'] = date('m-d', $row['day']);
                $row['daynum'] = intval(date('d', $row['day']));
                $row['fulldate'] = date('Y-m-d', $row['day']);
                $row['digital'] = intval(date('d', $row['day']));
                $row['adultprice'] = Currency_Tool::price($row['adultprice']);
            }
            if ($need_full_days)
            {
                $insert_day = $days - count($result);
                if ($insert_day)
                {
                    for ($i = 0; $i < $insert_day; $i++)
                    {
                        $r = array(
                            'adultprofit' => 0,
                            'adultbasicprice' => 0,
                            'adultprice' => 0
                        );
                        array_unshift($result, $r);
                    }
                }
            }

            if (empty($result))
            {
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key'], false, '获取最新报价失败', '获取最新报价失败');
            }
            else
            {
                $out = array(
                    'list' => $result
                );
                $this->send_datagrams($this->client_info['id'], $out , $this->client_info['secret_key']);
            }

        }


    }


    public function action_range_price()
    {
        $suitid = intval($this->request_body->content->suit_id);
        $startdate = St_Filter::remove_xss($this->request_body->content->start_date);
        $enddate = St_Filter::remove_xss($this->request_body->content->end_date);

        $dingnum = intval($this->request_body->content->ding_num);
        $price = Model_Car::suit_range_price($suitid, $startdate, $enddate, $dingnum);
        $price = $price * $dingnum;
        $result = array(
            'price' => $price
        );
        $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

    }
    /**
     * @desc 创建订单
     */
    public function action_create_order()
    {

        $order = array(
            'webid'   => 0,
            'addtime' => time(),
        );

        $type_id = $this->request_body->content->typeid;
        if ($type_id)
        {
            $typeid = intval($type_id);
            $order['typeid'] = $typeid;
            $tmp = intval($typeid) < 10 ? '0' . $typeid : $typeid;
            $ordersn = St_Product::get_ordersn($tmp);
            $order['ordersn'] = $ordersn;

        }

        //产品id
        $product_autoid = $this->request_body->content->productautoid;
        if ($product_autoid)
        {
            $productautoid = intval($product_autoid);
            $order['productautoid'] = $productautoid;
            $order['litpic'] = DB::select('litpic')->from('car')->where('id', '=', $productautoid)->execute()->get('litpic');
        }

        //产品aid
        $product_autoaid = $this->request_body->content->productautoaid;
        if ($product_autoaid)
        {
            $productautoaid = intval($product_autoaid);
            $order['productautoaid'] = $productautoaid;
        }

        //产品名称
        $product_name = $this->request_body->content->productname;
        if ($product_name)
        {
            $productname = Common::remove_xss($product_name);
            $order['productname'] = $productname;
        }

        //成人价格
        $adult_price = $this->request_body->content->price;
        if ($adult_price)
        {
            $price = Common::remove_xss($adult_price);
            $order['price'] = $price;
        }

        //联系人
        $link_man = $this->request_body->content->linkman;
        if ($link_man)
        {
            $linkman = Common::remove_xss($link_man);
            $order['linkman'] = $linkman;
        }

        //联系电话
        $link_tel = $this->request_body->content->linktel;
        if ($link_tel)
        {
            $linktel = Common::remove_xss($link_tel);
            $order['linktel'] = $linktel;
        }

        //备注说明
        $re_mark = $this->request_body->content->remark;
        if ($re_mark)
        {
            $remark = Common::remove_xss($re_mark);
            $order['remark'] = $remark;
        }

        //会员id
        $member_id = $this->request_body->content->memberid;
        if ($member_id)
        {
            $memberid = intval($member_id);
            $order['memberid'] = $memberid;
        }

        //套餐id
        $suit_id = $this->request_body->content->suitid;
        if ($suit_id)
        {
            $suitid = intval($suit_id);
            $order['suitid'] = $suitid;
        }

        //成人数量
        $ding_num = $this->request_body->content->dingnum;
        if ($ding_num)
        {
            $dingnum = intval($ding_num);
            $order['dingnum'] = $dingnum;
        }

        //支付方式
        $pay_type = $this->request_body->content->paytype;
        if ($pay_type)
        {
            $paytype = intval($pay_type);
            $order['paytype'] = $paytype;

        }

        //订金金额
        $ding_jin = $this->request_body->content->dingjin;
        if ($ding_jin)
        {
            $dingjin = intval($ding_jin);
            $order['dingjin'] = $dingjin;
        }

        //出发日期
        $use_date = $this->request_body->content->usedate;
        if ($use_date)
        {
            $usedate = $use_date;
            $order['usedate'] = $usedate;
        }

        $departdate = $this->request_body->content->departdate;
        if ($departdate)
        {
            $order['departdate'] = $departdate;
        }

        //套餐信息
        $suitInfo = Model_Line_Suit::suit_info($order['suitid']);
//        //自动关闭订单时间
//        $auto_close_time = $suitInfo['auto_close_time'] ? $suitInfo['auto_close_time'] : 0;
//        if ($auto_close_time)
//        {
//            $order['auto_close_time'] = $auto_close_time + time();;
//        }
        $need_confirm = $suitInfo['need_confirm']?$suitInfo['need_confirm']:0;
        $order['need_confirm']=$need_confirm;
        $order['status']=$need_confirm==1?0:1;
        // 订单来源 1PC,2WAP,3小程序,4平台添加
        $order['source'] = 3;

        if ($order['memberid'])
        {
            $out = Model_Api_Standard_Order::add_order($order, 'Model_Car');
            if ($out['status'])
            {
                $order_id = DB::select('id')->from('member_order')->where('ordersn', '=', $order['ordersn'])->execute()->get('id');
                $order['orderid'] = $order_id;
                $order_info['need_confirm'] = $need_confirm;
                $result = array(
                    'status'    => true,
                    'orderinfo' => $order,
                );
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);
            } else
            {
                $result = array(
                    'status' => false,
                    'msg'    => $out['msg'],
                );
                $this->send_datagrams($this->client_info['id'], $result, $this->client_info['secret_key']);

            }
        }


    }

    /**
     * 获取车型列表
     */
    public function action_get_attr_list()
    {
        $attrid = $this->request_body->content->attrid;
        $offset = $this->request_body->content->page;
        $row = $this->request_body->content->pagesize;
        $offset = empty($offset) ? 0 : $offset*$row;

        $w = " where a.ishidden=0 and a.carkindid = {$attrid} ";
        $orderBy = "ORDER BY IFNULL(b.displayorder,9999) asc,a.modtime desc,a.addtime desc";
        $sql = "SELECT a.id,a.webid,a.sellpoint,a.aid,a.kindlist,a.title,a.litpic,a.shownum,a.price,a.price_date,a.satisfyscore,";
        $sql .= "a.bookcount,a.attrid,a.iconlist,a.carkindid FROM sline_car a LEFT JOIN sline_allorderlist b";
        $sql .= " ON(a.id=b.aid AND b.typeid=3) {$w} {$orderBy}  limit {$offset},{$row}";
        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();

        foreach($list as &$v)
        {
            $v['litpic'] = Common::img($v['litpic']);
            $v['attrlist'] = Model_Car_attr::get_attr_list($v['attrid']);
            $v['commentnum'] = Model_Comment::get_comment_num($v['id'], 3); //评论次数
            $v['score'] = St_Functions::get_satisfy(3, $v['id'], $v['satisfyscore']);
            $kindmame = '';
            if(!empty($v['kindlist']))
            {
                $newsql = "SELECT kindname FROM sline_destinations where id in({$v['kindlist']})";
                $kindmame = DB::query(Database::SELECT,$newsql)->execute()->as_array();
            }
            $v['kindname'] = $kindmame;
            $v['score'] = St_Functions::get_satisfy(3, $v['id'], $v['satisfyscore']);
            $v['price'] = Currency_Tool::price($v['price']);;
        }
        $this->send_datagrams($this->client_info['id'], $list, $this->client_info['secret_key']);
    }

    /**
     * 根据日期范围获取产品总价
     */
    public function action_get_time_count_price()
    {
        $productid = $this->request_body->content->productid;
        $suitid = $this->request_body->content->suitid;
        $starttime = empty($this->request_body->content->starttime) ? strtotime(date('Y-m-d')) : strtotime($this->request_body->content->starttime);
        $endtime = empty($this->request_body->content->endtime) ? strtotime(date('Y-m-d')) : strtotime($this->request_body->content->endtime);
        $sql = "SELECT SUM(adultprice) as price from sline_car_suit_price where carid={$productid} and supplier_channel_id=1 and suitid={$suitid} and day >={$starttime} and day<={$endtime}";
        $list = DB::query(Database::SELECT, $sql)->execute()->current();
        $this->send_datagrams($this->client_info['id'], $list, $this->client_info['secret_key']);

    }
}